package com.leo.base.db.router.rule;

import com.leo.base.db.router.function.MurmurHash;
import com.leo.base.db.router.util.PartitionUtil;
import org.springframework.beans.factory.InitializingBean;

/**
 * 分片路由规则
 */
public class ShardingRule implements InitializingBean, IRule {

    private String[] dataSourceKey;
    private String shardingField;
    private int[] count;
    private int[] length;

    private PartitionUtil partitionUtil;

    @Override
    public String getDataSourceKey(String shardingFieldValue) {
        Long hash = MurmurHash.hash(shardingFieldValue);
        int partition = partitionUtil.partition(hash);
        return dataSourceKey[partition];
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        partitionUtil = new PartitionUtil(count, length);
    }

    public void setDataSourceKey(String[] dataSourceKey) {
        this.dataSourceKey = dataSourceKey;
    }

    public void setShardingField(String shardingField) {
        this.shardingField = shardingField;
    }

    public void setCount(int[] count) {
        this.count = count;
    }

    public void setLength(int[] length) {
        this.length = length;
    }

    public String getShardingField() {
        return shardingField;
    }
}
